package logic_login

import (
	v1 "Sailor/app/Sailor-console-server/api/api_login/v1"
	"Sailor/app/Sailor-console-server/internal/dao"
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"Sailor/app/Sailor-console-server/utility/utility_hash"
	"Sailor/app/Sailor-console-server/utility/utility_jwt"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

func (s *sLogin) LogicLogin(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
	var user entity.SysUser
	err = dao.SysUser.Ctx(ctx).
		Where(dao.SysUser.Columns().UserAccount, req.UserName).Scan(&user)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, gerror.New("用户不存在")
		}
		g.Log().Error(ctx, err)
		return nil, gerror.New("登陆失败")
	}
	if user.UserStatus != 1 {
		return nil, gerror.New("用户已被禁止登陆")
	}

	if !utility_hash.CheckPwd(user.UserPassword, req.Password) {
		return nil, gerror.New("密码错误")
	}

	expireTime, token, err := utility_jwt.GenerateToken(ctx, user)
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("登陆失败")
	}

	return &v1.LoginRes{
		Token:      token,
		ExpireTime: expireTime,
		UserInfo:   user,
	}, nil
}
